package edu.yctc.patterns.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import edu.yctc.patterns.constant.ResultCode;
import edu.yctc.patterns.constant.entity.tag.UserTag;
import edu.yctc.patterns.dao.UserDAO;
import edu.yctc.patterns.entity.ResultDO;
import edu.yctc.patterns.entity.UserDO;
import edu.yctc.patterns.service.UserIService;
import edu.yctc.patterns.util.SHA256Util;

/**
 * @className UserServiceImpl
 * @description 用户业务实现类
 * @author zyj
 * @date 2019年12月11日
 *
 */
@ComponentScan({"edu.yctc.patterns.dao"})
@Service("userService")
public class UserServiceImpl implements UserIService {

    private final static Logger LOG = LoggerFactory.getLogger("serviceLogger");

    @Resource
    private UserDAO userDAO;

    @Override
    public ResultDO<Long> signin(UserDO userDO) {
        // 检验参数
        if (StringUtils.isBlank(userDO.getAccount()) || StringUtils.isBlank(userDO.getPassword())
            || UserTag.isLegal(userDO.getTag()) == false) {
            LOG.error("signin fail, parameter invalid, userDO={}", userDO);
            return new ResultDO<Long>(false, ResultCode.PARAMETER_INVALID, ResultCode.MSG_PARAMETER_INVALID, null);
        }
        try {
            UserDO toSignin = userDAO.getUserDOByAccountAndPasswordAndTag(userDO.getAccount(),
                SHA256Util.SHA256(userDO.getPassword()), userDO.getTag());
            if (toSignin == null) {
                LOG.error("signin fail, no such user, userDO={}", userDO);
                return new ResultDO<Long>(false, ResultCode.INCORRECT_NUMBER_OR_PASSWORD,
                    ResultCode.MSG_INCORRECT_NUMBER_OR_PASSWORD, null);
            }
            LOG.info("signin success, userDO={}", userDO);
            return new ResultDO<Long>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS, toSignin.getId());
        } catch (Exception e) {
            LOG.error("signin error, userDO={}", userDO, e);
            return new ResultDO<Long>(false, ResultCode.ERROR_SYSTEM_EXCEPTION, ResultCode.MSG_ERROR_SYSTEM_EXCEPTION,
                null);
        }
    }

}
